﻿using DAL;
using DianShangHouTai.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DianShangHouTai.Controllers
{
    public class CustomerController : Controller
    {
        // GET: Customer客户管理
        public ActionResult Index()
        {
            return View();
        }/// <summary>
        /// 搜索
        /// </summary>
        /// <returns></returns>
        public ActionResult Search()
        {
            using (ShopContext db = new ShopContext())
            {
                string CustomerPhone = Request.Params["CustomerPhone"];
                string CustomerName = Request.Params["CustomerName"];
                int pn, pz;
                if (!int.TryParse(Request.Params["page"], out pn))
                {
                    pn = 1;
                }
                if (!int.TryParse(Request.Params["Limit"], out pz))
                {
                    pn = 10;
                }
                try
                {
                    IQueryable<Customer> res = db.Customer.Where(p => true);
                    if (!string.IsNullOrWhiteSpace(CustomerPhone))
                    {
                        res = res.Where(x => x.CustomerPhone==CustomerPhone);
                    }
                    if (!string.IsNullOrWhiteSpace(CustomerName))
                    {
                        res = res.Where(x => x.CustomerName == CustomerName);
                    }
                    var list = res.OrderByDescending(p => p.Id).Skip((pn - 1) * pz).Take(pz).ToList();
                    //return Json(new { code=0, msg = "", count =res.Count() , data = list });
                    return Content(Pager.PagedData<Customer>(list, res.Count()));
                }
                catch (Exception ex)
                {
                    return Json(new { code = 1, msg = "查询出错:" + ex.Message, data = new List<Customer>(), count = 0 }, JsonRequestBehavior.AllowGet);
                    throw;
                }

            }            
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        [HttpGet]
       public ActionResult Add()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Add(UICustomer data)
        {
            using(ShopContext db=new ShopContext())
            {
                try
                {
                    Customer ds = new Customer
                    {
                        CustomerName = data.CustomerName,
                        CustomerPassWord = "123456",
                        CustomerNiCheng = data.CustomerNiCheng,
                        CustomerSex = data.CustomerSex== "男" ? "男" : "女",
                        CustomerTouXiang = "5",
                        CustomerPhone = data.CustomerPhone,
                        CustomerEmail ="123456",
                        CustomerLoginTime = DateTime.Now
                    };

                    db.Customer.Add(ds);

                    int r = db.SaveChanges();
                    if (r > 0)
                    {  
                        return Json(new UIResult(true, ""));
                    }
                    else          
                        return Json(new UIResult(false, "未知原因添加失败"));
                }
               catch (Exception ex)
                {
                    return Json(new UIResult(false, ex.Message));
                }
            }
        }
        /// <summary>
        /// 删除  
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Del(string id)
        {
            using (ShopContext db = new ShopContext())
            {
                int a = Convert.ToInt32(id);
                var ds = db.Customer.SingleOrDefault(p => p.Id == a);
                if (ds != null)
                {
                    db.Customer.Remove(ds);
                    db.SaveChanges();
                    return Json(new { success = true, msg = "删除成功" });
                }
                else
                {
                    return Json(new { success = false, msg = "删除失败" });
                }
            }

        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Pubdel(string ids)
        {
            using (ShopContext db = new ShopContext())
            {
                if (ids != null )
                {
                    string sql = string.Format("delete from Customers where[Id] in ({0})", ids, DateTime.Now);
                    try
                    {
                        int res = db.Database.ExecuteSqlCommand(sql);
                        if (res > 0)
                        {
                            return Json(new { code = 0 ,msg="删除成功"});
                        }
                        else
                            return Json(new { code = 1 , msg = "删除成功失败" });
                    }
                    catch (Exception ex)
                    {
                        return Json(ex.Message);

                    }
                }
                else
                {
                    return Json(new { code = 1, msg = "删除失败" });
                }
            }
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit( int ? Id)
        {
            using (ShopContext db=new ShopContext())
            {
                Customer ats = db.Customer.SingleOrDefault(x => x.Id == Id);
            return View(ats);
            }
          
        }
        [HttpPost]
        public ActionResult Edit(UICustomer data)
        {
            using(ShopContext db=new ShopContext())
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                    var obj = db.Customer.SingleOrDefault(p => p.Id == data.Id);
                        obj.CustomerName = data.CustomerName;
                        obj.CustomerNiCheng = data.CustomerNiCheng;
                        obj.CustomerPassWord = data.CustomerPassWord;
                        obj.CustomerSex = data.CustomerSex == "男" ? "男" : "女";
                        obj.CustomerPhone = data.CustomerPhone;
                        obj.CustomerEmail = data.CustomerEmail;
                    
                        if (db.SaveChanges() > 0)
                        {
                            return Json(new UIResult(true, ""));
                        }
                        else
                        {
                            return Json(new UIResult(false, "未知原因修改错误"));
                        }
                        
                    }
                    else
                    {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        int i = 1;
                        foreach (var s in ModelState.Values)
                        {
                            foreach (var p in s.Errors)
                            {
                                sb.AppendFormat("{0}-{1}", i++, p.ErrorMessage);
                            }
                        }
                        return Json(new UIResult(false, "服务器未通过" + sb));
                    }
                }
                catch (Exception ex)
                {
                    return Json(new UIResult(false, ex.Message));
                    throw;
                }
            }
            
        }
        /// <summary>
        /// 购物车管理
        /// </summary>
        /// <returns></returns>
        public ActionResult ShoppingCart()
        {
            return View();
        }      
        /// <summary>
        /// 收藏管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Collection()
        {
            return View();

        }
        /// <summary>
        /// 订单管理
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderDetl()
        {
            var list = db.View_Order_Detiles.Where(p => true).Select(p => p.FaHuoZhuangTai).Distinct().ToList();
            List<SelectListItem> arrs = new List<SelectListItem>();
            foreach (var item in list)
            {
                arrs.Add(new SelectListItem { Text = item, Value = item });
            }
            ViewBag.FaHuoZhuangTai = arrs;//发货状态查询
            return View();
        }
        ShopContext db = new ShopContext();
        /// <summary>
        /// 订单查询
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderDels()
        { 
                string CustomerPhone = Request.Params["Phone"];
            string selTypes = Request.Params["FaHuoZhuangTai"];//类别名称
            int pn, pz;
                if (!int.TryParse(Request.Params["page"], out pn))
                {
                    pn = 1;
                }
                if (!int.TryParse(Request.Params["Limit"], out pz))
                {
                    pn = 10;
                }
                try
                {
                IQueryable<View_Order_Detiles> res = db.View_Order_Detiles.Where(p => true);
                    if (!string.IsNullOrWhiteSpace(CustomerPhone))
                    {
                        res = res.Where(p => p.Phone.Contains(CustomerPhone));
                    }
                if (!string.IsNullOrWhiteSpace(selTypes))
                {
                    res = res.Where(p => p.FaHuoZhuangTai == selTypes);
                }
                    var list = res.OrderByDescending(p => p.Id).Skip((pn - 1) * pz).Take(pz).ToList();
                    return Content(Pager.PagedData<View_Order_Detiles>(list, res.Count()));
                }
                catch (Exception ex)
                {
                    return Json(new { code = 1, msg = "查询出错:" + ex.Message, data = new List<View_Order_Detiles>(), count = 0 }, JsonRequestBehavior.AllowGet);
                    throw;
                }

            
        }
        /// <summary>
        /// 订单编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderDetlEdit(int? id)
        {
            Order ats = db.Order.SingleOrDefault(x => x.OrderId == id);
            return View(ats);
        }
        [HttpPost]
        public ActionResult OrderDetlEdit(UIOrderDetlEdit data)
        {

                    var obj = db.Order.SingleOrDefault(p => p.OrderId == data.OrderId);
                    obj.Address  = data.Address;
                    obj.Phone = data.Phone;
                    obj.KeHuName = data.KeHuName;
        
                    int i = db.SaveChanges();
                    if (i > 0)
                    {
                        return Json(new UIResult(true, "更新成功"));
                    }
                    else
                    {
                        return Json(new UIResult(false, "更新失败"));
                    }
             
        
    }
        /// <summary>
        /// 发货
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult FaHuo(int? id)
        {
            try
            {
                var obj = db.Order.SingleOrDefault(p => p.OrderId == id);
                if (obj.FaHuoZhuangTai != "已发货")
                {
                    obj.FaHuoZhuangTai = "已发货";
                }
                if (db.SaveChanges() > 0)
                {
                    return Json(new UIResult(true, "成功发货"));
                }
                else
                {
                    return Json(new UIResult(false, "请勿多次发货"));
                }
            }
            catch (Exception ex)
            {

                return Json(new UIResult(false, "出错了:" + ex.Message));
            }

        }
        /// <summary>
        /// 取消发货
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ISFaHuo(int? id)
        {
            try
            {
                var obj = db.Order.SingleOrDefault(p => p.OrderId == id);
                if (obj.FaHuoZhuangTai != "未发货")
                {
                    obj.FaHuoZhuangTai = "未发货";
                }
                if (db.SaveChanges() > 0)
                {
                    return Json(new UIResult(true, "取消发货成功"));
                }
                else
                {
                    return Json(new UIResult(false, "货物已发货，无法取消"));
                }
            }
            catch (Exception ex)
            {

                return Json(new UIResult(false, "出错了:" + ex.Message));
            }

        }
        /// <summary>
        /// 地址管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Address()
        {
            return View();
        }
        public ActionResult Collections()
        {
            List<Address> users = db.Address.Where(p => true).ToList();
            return Content(Pager.PagedData<Address>(users, users.Count()));
        }
    }
}